package com.qiche.controller.mgr;

import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.config.YmlConfig;
import com.qiche.dto.CardDto;
import com.qiche.enums.ResultEnum;
import com.qiche.exception.MySystemException;
import com.qiche.model.*;
import com.qiche.service.*;
import com.qiche.util.ApplicationUtils;
import com.qiche.util.UserUtils;
import com.qiche.vo.BatchPostCardVo;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 卡券管理控制器
 *
 * @author Linzewen
 * <p>
 * 2018年2月27日
 */
@Api(value = "/cards", description = "卡券管理控制器")
@RestController
@RequestMapping("/cards")
public class CardController {
    @Resource
    private MerchantService merchantService;
    @Resource
    private InsurancePolicyService policyService;
    @Resource
    private CardService cardService;
    @Autowired
    private StoreMemberService storeMemberService;

    @Autowired
    private ComboMasterService comboMasterService;
    @Autowired
    private ComboDetailService comboDetailService;
    @Autowired
    private ProductService productService;
    @Autowired
    private YmlConfig ymlConfig;

    @ApiOperation(value = "根据条件和分页获取卡券列表")
    @GetMapping
    public Map<String, Object> getAll(Card card,
                                      @RequestParam(required = false, defaultValue = "1") int page,
                                      @RequestParam(required = false, defaultValue = "10") int limit) {
        Map<String, Object> map = new HashMap<>();
        // 根据门店区筛选
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();

        if (currentUser.getMerchantId() != 0 && currentUser.getMerchantId() != null) {
            card.setMerchantId(currentUser.getMerchantId().longValue());
        }

        List<CardDto> cardDtos = new ArrayList<>();
        PageInfo<Card> pageInfo = cardService.selectByPage(card, page, limit);

        for (Card tcard : pageInfo.getList()) {
            CardDto dto = new CardDto();
            BeanUtils.copyProperties(tcard, dto);
            dto.setBelongMerchantName(merchantService.selectById(tcard.getMerchantId()).getName());
            cardDtos.add(dto);
        }
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", cardDtos);
        return map;
    }

    @ApiOperation(value = "根据会员ID获取 门店客户员信息 附带该客户的保单列表")
    @GetMapping(value = "/getById/{customerId}")
    public Map<String, Object> getById(@PathVariable(name = "customerId") Long customerId) {
       StoreMember storeMember=storeMemberService.selectByKey(customerId);
        List<InsurancePolicy> policys = policyService.selectByCustomerId(storeMember.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("bean", storeMember);
        map.put("policys", policys);
        return map;
    }

    @ApiOperation(value = "执行发卡")
    @PostMapping(value = "/postCard")
    public Result postCard(@RequestParam("id") Long packId) {
        if (packId == null) {
            throw new MySystemException(ResultEnum.PARAM_ERROR);
        }
        return cardService.postCard(packId);
    }


    @ApiOperation(value = "核销根据卡号判断卡券是否可用")
    @GetMapping(value = "/isused/{cardcode}")
    public Result isUsed(@PathVariable("cardcode") String cardcode) throws Exception {
        if (StringUtils.isBlank(cardcode)) {
            throw new MySystemException(ResultEnum.PARAM_ERROR);
        }
        return cardService.isUsed(cardcode);
    }


    @ApiOperation(value = "根据客户ID获取门店卡券列表")
    @GetMapping(value = "/getListByCustomerId/{customerId}")
    public Result<List<Card>> getListByCustomerId(@PathVariable("customerId") Long customerId) {
        List<Card> cards = cardService.selectByCustomerId(customerId);
        return Result.createBySuccess(cards);
    }

    @ApiOperation(value = "根据选中的客户列表批量发券")
    @PostMapping(value = "/batchPostCard")
    public Result batchPostCard(@RequestBody BatchPostCardVo batchPostCardVo) {
        Long masterId = batchPostCardVo.getMasterId();
        //判断是否可用
        ComboMaster comboMaster=comboMasterService.selectByKey(masterId);
        if(comboMaster!=null &&comboMaster.getStatus()==0){
            return Result.createByErrorMessage("套餐已停用");
        }
        List<Integer> customerIdList = batchPostCardVo.getCustomerIdList();
       // List<Card> toSendCards = comboMasterConvertToCards(masterId);

        List<Card> totalSendCards = new ArrayList<>();
        //循环客户发券
        for (Integer customerId : customerIdList) {
            StoreMember storeMember=storeMemberService.selectByKey(customerId);
            if (storeMember != null) {
                for (Card card : comboMasterConvertToCards(masterId)) {
                    card.setCustomerId(storeMember.getId());
                    card.setCustomerName(storeMember.getName());
                    card.setCustomerPhone(storeMember.getPhone());
                    totalSendCards.add(card);
                }
            }
        }
        int insertCount = cardService.batchInsert(totalSendCards);
        if (insertCount > 0) {
            return Result.createBySuccessMessage("批量发券成功");
        }
        return Result.createByErrorMessage("批量发券失败");
    }


    public List<Card> comboMasterConvertToCards(Long comboMatserId) {
        List<Card> toSendCards = new ArrayList<>();
        ComboMaster comboMaster = comboMasterService.selectByKey(comboMatserId);
        List<ComboDetail> comboDetailList = comboDetailService.selectByMasterId(comboMaster.getId().intValue());
        if (!comboDetailList.isEmpty()) {
            Calendar calendar = Calendar.getInstance();
            for (ComboDetail comboDetail : comboDetailList) {
                for (int i = 0; i < comboDetail.getQuantity(); i++) {
                    calendar.setTime(new Date()); // 每次循环时间都要复位
                    Product product = productService.selectById(comboDetail.getProductId());
                    Card card = new Card();  //汽车系统的卡券
                    card.setCardCode(ymlConfig.getQicheSystemCardPrefix() + ApplicationUtils.getRandomString(16));
                    card.setCardType("service");
                    card.setCreateDate(new Date());
                    card.setStatus("1");
                    if (product != null) {
                        card.setCardAmount(product.getPrice().longValue());
                        card.setCardTitle(product.getName());
                    }
                    card.setAvailable("周一,周二,周三,周四,周五,周六,周日");
                    // card.setAvailable(piccCard.getAvailable());
                    card.setIsWriteoff(0); // 1：已核销 2：未核销
                    card.setWriteoffDate(null);
                    card.setVerifyBeginDate(new Date()); // 当前时间为可核销开始时间
                    calendar.add(Calendar.MONTH, comboMaster.getUsePeriod());// 根据产品的有效期来定
                    card.setVerifyEndDate(calendar.getTime());
                    card.setMerchantId(UserUtils.getCurrentUser().getMerchantId().longValue());

                    toSendCards.add(card);
                }
            }
        }
        return toSendCards;
    }

}
